﻿# encoding=utf-8
import platform
import subprocess
from test_tools.script.path_tool import *
from test_tools.view.excel_tools_message_view import ExcelToolsMessageView
from test_tools.script import _proton

# 配置启动信息
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0  # 0 表示隐藏窗口

pythonpath = "tools/py37/py37.exe " if platform.system() == 'Windows' else 'python'
CSharpGeneratorForProton = 'CSharpGeneratorForProton\CSharpGeneratorForProton.exe '


class ExportError(Exception):
    pass


def codegenerator(schema, outfolder, namespace, suffix):
    if os.path.exists(schema):
        cmd = CSharpGeneratorForProton + '-n ' + namespace + ' -f ' + outfolder + ' -p ' + schema
        if suffix:
            cmd += ' -t ' + suffix
            code = os.system(cmd)
            if code != 0:
                log("export-> codegenerator-> 【【【【命令运行失败】】】】")
                raise ExportError('codegenerator-> 【【【【导出 excel 失败, 请看控制台输出】】】】')
        os.remove(schema)


def print_path():
    """输出脚本和程序工作目录"""
    log("==========输出脚本和程序工作目录==========")
    current_dir = os.path.dirname(os.path.abspath(__file__))
    working_dir = os.getcwd()
    log(f"当前脚本 {os.path.basename(__file__)} 运行目录： {current_dir}")
    log(f"当前程序工作目录：{working_dir}")
    log("======================================")


class Export:
    def __init__(self):
        print_path()
        self.__print = my_print.print
        self.__message = ExcelToolsMessageView()
        self.log_list = []

    def export_excel(self, filelist, _format, outfolder, suffix, schema):
        """
        执行导表操作
        """
        log(f"export-> export_excel-> filelist: {filelist},outfolder: {outfolder}")
        # cmd = r' -p "' + ','.join(filelist) + '" -f ' + outfolder + ' -e ' + _format + ' -s ' + sign + ' -m ' + "1"
        cmd = r' -p "' + ','.join(filelist) + '" -f ' + outfolder + ' -e ' + _format
        if suffix:
            cmd += ' -t ' + suffix
        if schema:
            cmd += ' -c ' + schema
        # cmd = pythonpath + self.__path_tool.proton_path + cmd
        # cmd = pythonpath + proton_path + cmd
        # self.do_cmd(cmd)
        path = ','.join(filelist)
        folder = outfolder
        _format = _format
        extension = suffix
        try:
            self.__print('==================== excel -> json 开始 ====================')
            _proton.main(path, folder, _format, extension)
            self.__print('==================== excel -> json 完成 ====================')
        except Exception as e:
            self.__print(f'**************** 执行导表操作 失败 ****************', 1)
            prin_error()
            self.__message.show_message(f"{os.path.basename(__file__)} >>> 执行导表操作 异常：{e}")
            raise e

    def do_cmd(self, cmd, get_log=False):
        """使用控制台执行CMD命令"""
        log(f"export-> do_cmd-> cmd: {cmd}")
        try:
            self.__print(f"============= 开始执行控制台命令 =============\nCMD: {cmd}")
            result = subprocess.run(cmd, check=True, capture_output=True, text=True, shell=True)
            if get_log:
                self.log_list.clear()
                self.log_list.append(result.stdout)
            self.__print(f"{result.stdout}")
            log(result.stdout)
            self.__print(f"============= 控制台命令执行完毕 =============")
        except Exception as e:
            self.__print(f'**************** 执行控制台命令 失败 ****************', 1)
            prin_error()
            self.__message.show_message(f"{os.path.basename(__file__)} >>> 执行控制台命令 异常：{e}")

    def do_cmd_stream(self, cmd, get_log=False):
        """使用控制台执行CMD命令，输出持续流"""
        log(f"export-> do_cmd_stream-> cmd: {cmd}")
        try:
            self.__print(f"============= 开始执行控制台命令 =============\nCMD: {cmd}")
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                stdin=subprocess.PIPE,
                startupinfo=startupinfo,  # 关键：隐藏窗口
                text=True
            )
            if get_log:
                self.log_list.clear()
            while True:
                line = process.stdout.readline()
                line = line.strip()  # 去除首尾空白字符（包括换行符）
                if not line:  # 若为空字符串（原行仅含空白字符）
                    if process.poll() is not None:  # 检查子进程是否结束
                        break
                    continue  # 跳过当前行
                if get_log:
                    self.log_list.append(line)
                self.__print(f"{line}")  # 仅打印非空白行
                log(line)
            self.__print(f"============= 控制台命令执行完毕 =============")
        except Exception as e:
            self.__print(f'**************** 执行控制台命令 失败 ****************', 1)
            prin_error()
            self.__message.show_message(f"{os.path.basename(__file__)} >>> 执行控制台命令 异常：{e}")

    def exportclient(self, tables):
        """
        导出客户端配置文件
        """
        log(f"export-> exportclient-> tables: {tables}")
        # export(tables, 'lua', 'client', path_tool.dirClient, '_config', None)
        # codegenerator('schemaserver.json', 'config_server/ConfigGenerator/Template', 'Ice.Project.Config', 'Template')
        # 导出客户但端配置文件
        self.export_excel(tables, 'json', dirClient, '_config', None)

    def exportserver(self):
        """
        筛选服务器配置文件
        """
        log(f"export-> exportserver")
        configList = []
        try:
            # 读取配置文件
            with open(server_config_path, encoding='utf-8', mode='r') as f:
                contents = f.readlines()
        except Exception as e:
            self.__print(f'**************** 筛选服务器配置文件 失败 ****************', 1)
            prin_error()
            self.__message.show_message(f"{os.path.basename(__file__)} >>> 筛选服务器配置文件 异常：{e}")
            return

            # 去除配空格和换行符
        for line in contents:
            configList.append(line.strip())
        # 遍历导表目录，将导出来的json文件筛选出服务器需要的文件，复制到服务器目录中
        for filepath, dirNames, filenames in os.walk(dirClient):
            if len(filenames) > 0:
                self.__print(f"【开始复制 json 文件到后端配置文件目录 {dirServer}】")
                for filename in filenames:
                    if filename in configList:
                        _path = os.path.join(filepath, filename)
                        shutil.copy(str(_path), dirServer)
                        self.__print(f"{filename} 》》》 复制完成")
            else:
                self.__print("【本次导表无服务器所需上传配置】")
                return

    def check_server_config(self):
        """
        判断server_config.txt文件是否存在，不存在则创建，并删除time.txt文件
        return: 返回文件是否存在和文件长度
        """
        log(f"export-> check_server_config")
        _len = 0
        self.__print(f'正在执行：判断server_config.txt文件是否存在')
        if not os.path.exists(server_config_path):  # 判断server_config.txt文件是否存在
            with open(server_config_path, 'w'):  # 不存在则创建
                pass
            self.__print(f"{server_config_path} 文件不存在，已创建")
            return False, _len
        else:
            try:
                with open(server_config_path, encoding='utf-8', mode='r') as f:
                    contents = f.readlines()
            except Exception as e:
                self.__print(f'**************** 判断server_config.txt文件是否存在 失败 ****************', 1,
                             )
                prin_error()
                self.__message.show_message(
                    f"{os.path.basename(__file__)} >>> 判断server_config.txt文件是否存在 异常：{e}")
                return False, _len
            _len = len(contents)
            if _len == 0:
                self.__print(f"{server_config_path} 文件内容为空", 1)
                return False, _len
            else:
                return True, _len

    def main(self, tables):
        """执行导表操作"""
        log(f"export-> main")
        try:
            # exportserver(tables)
            # time.sleep(0.5)
            clear_dir(dirClient)
            clear_dir(dirServer)
            self.exportclient(tables)
            self.exportserver()
        except Exception as e:
            traceback.print_exc()
            self.__print(f'**************** 执行导表操作 失败 ****************', 1)
            prin_error()
            self.__message.show_message(f"{os.path.basename(__file__)} >>> 执行导表操作 异常：{e}")

# if __name__ == '__main__':
#     def run(cmd):
#         print("=================================================")
#         result = subprocess.run(cmd, check=True, capture_output=True, text=True,shell=True)
#         print(result.stdout)
#         print("=================================================")
#
#     run("svn cleanup excel --remove-unversioned")
#     run("svn revert -R excel")
#     run("svn update -r 23403 excel")
#     run("svn diff excel -r 23367:23403 --summarize")
